package algorithm;

/**
 * @ Author     ：wangyw
 * @ Date       ：Created in 5:26 下午 2021/4/16
 * @ Description：
 */
public class LRUList<T> {

    private Node list;
    private int size;

    // 添加节点
    public void put(T data) {
        Node node = new Node(data, list);
        list = node;
        size++;
    }

    public void put(int index, T data) {
        checkIndex(index);
        Node curr = list;
        Node front = null;
        for (int i = 0; i < index; i++) {
            front = curr;
            curr = curr.next;
        }
        Node newNode = new Node(data, curr);
        front.next = newNode;
        size++;
    }

    // 删除节点
    public T remove() {
        Node removeNode = list;
        list = list.next;
        size--;
        return removeNode.data;
    }
    public T remove(int index) {
        checkIndex(index);
        Node curr = list;
        Node front = null;
        for (int i = 0; i < index; i++) {
            front = curr;
            curr = curr.next;
        }
        front.next = curr.next;
        size--;
        return curr.data;
    }

    // 获取数据
    public T get() {
        return list.data;
    }
    public T get(int index) {
        Node curr = list;
        for (int i = 0; i < index; i++) {
            curr = curr.next;
        }
        return curr.data;
    }

    private void checkIndex(int index) {
        if (!(index > 0 && index <= size)) {
            throw new IndexOutOfBoundsException("out of index, index:" + index + ", size:" + size);
        }
    }

    // 更新节点数据
    public void update(int index, T data) {
        checkIndex(index);
        Node curr = list;
        for (int i = 0; i < index; i++) {
            curr = curr.next;
        }
        curr.data = data;
    }

    @Override
    public String toString() {
        String ret = "";
        Node node = list;
        while (node.next != null) {
            ret += node.data + " ";
            node = node.next;
        }
        return ret + node.data;
    }

    class Node {
        private T data;
        private Node next;

        public Node(T data, Node next) {
            this.data = data;
            this.next = next;
        }
    }

    public static void main(String[] args) {
        LRUList<Integer> lruList = new LRUList<Integer>();
        for (int i = 0; i < 5; i++) {
            lruList.put(i);
        }
        System.out.println("lruList = " + lruList);
        lruList.put(2, 5);
        System.out.println("lruList = " + lruList);
        lruList.remove();
        System.out.println("lruList = " + lruList);
        lruList.remove(3);
        System.out.println("lruList = " + lruList);
        System.out.println("lruList.get() = " + lruList.get());
        System.out.println("lruList.get(2) = " + lruList.get(2));
        lruList.update(1, 10);
        System.out.println("lruList = " + lruList);
    }
}
